package com.ruoyi.iot.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.framework.minio.MinioFile;
import com.ruoyi.framework.minio.MinioService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.iot.domain.FacDeviceFile;
import com.ruoyi.iot.service.IFacDeviceFileService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.iot.domain.FacDeviceBasic;
import com.ruoyi.iot.service.IFacDeviceBasicService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 设备基础Controller
 *
 * @author rww
 * @date 2024-06-22
 */
@RestController
@RequestMapping("/iot/basic")
public class FacDeviceBasicController extends BaseController
{
    @Autowired
    private IFacDeviceBasicService facDeviceBasicService;

    @Autowired
    private IFacDeviceFileService facDeviceFileService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private MinioService minioService;

    /**
     * 查询设备基础列表
     */
    @PreAuthorize("@ss.hasPermi('iot:basic:list')")
    @GetMapping("/list")
    public TableDataInfo list(FacDeviceBasic facDeviceBasic)
    {
        startPage();
        List<FacDeviceBasic> list = facDeviceBasicService.selectFacDeviceBasicList(facDeviceBasic);
        return getDataTable(list);
    }

    /**
     * 获取设备基础列表-不带分页
     */
    @GetMapping("/noPageList")
    public AjaxResult noPageList(FacDeviceBasic facDeviceBasic)
    {
        List<FacDeviceBasic> list = facDeviceBasicService.selectFacDeviceBasicList(facDeviceBasic);
        return AjaxResult.success(list);
    }

    /**
     * 便携设备 查询列表
     * @param facDeviceBasic
     * @return
     */
    @GetMapping("/bxsbList")
    public AjaxResult bxsbList(FacDeviceBasic facDeviceBasic){
        JSONObject result = new JSONObject();
        List<FacDeviceBasic> list = facDeviceBasicService.selectFacDeviceBasicList(facDeviceBasic);
        for(FacDeviceBasic item:list){
            FacDeviceFile queryEntity=new FacDeviceFile();
            queryEntity.setDeviceId(item.getId());
            List<FacDeviceFile> fileList = facDeviceFileService.selectFacDeviceFileList(queryEntity);
            item.setDeviceFileList(fileList);
        }
        result.put("list", list);
        return AjaxResult.success(result);
    }


    /**
     * 导出设备基础列表
     */
    @PreAuthorize("@ss.hasPermi('iot:basic:export')")
    @Log(title = "设备基础", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FacDeviceBasic facDeviceBasic)
    {
        List<FacDeviceBasic> list = facDeviceBasicService.selectFacDeviceBasicList(facDeviceBasic);
        ExcelUtil<FacDeviceBasic> util = new ExcelUtil<FacDeviceBasic>(FacDeviceBasic.class);
        util.exportExcel(response, list, "设备基础数据");
    }

    /**
     * 获取设备基础详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(facDeviceBasicService.selectFacDeviceBasicById(id));
    }

    /**
     * 获取设备基础详细信息
     */
    @GetMapping(value = "/getInfoNew")
    public AjaxResult getInfoNew()
    {
        FacDeviceBasic info = facDeviceBasicService.selectNewBxSbInfo();
        if(info==null){
            return warn("暂无设备!");
        }
        FacDeviceFile queryEntity=new FacDeviceFile();
        queryEntity.setDeviceId(info.getId());
        List<FacDeviceFile> fileList = facDeviceFileService.selectFacDeviceFileList(queryEntity);
        info.setDeviceFileList(fileList);
        return success(info);
    }

    /**
     * 新增设备基础
     */
    @PreAuthorize("@ss.hasPermi('iot:basic:add')")
    @Log(title = "设备基础", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FacDeviceBasic facDeviceBasic, HttpServletRequest request)
    {
        Long userId = tokenService.getLoginUser(request).getUserId();
        facDeviceBasic.setCreator(userId.toString());
        String userName=tokenService.getLoginUser(request).getUsername();
        facDeviceBasic.setCreatorName(userName);
        return toAjax(facDeviceBasicService.insertFacDeviceBasic(facDeviceBasic));
    }

    /**
     * 修改设备基础
     */
    @PreAuthorize("@ss.hasPermi('iot:basic:edit')")
    @Log(title = "设备基础", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FacDeviceBasic facDeviceBasic)
    {
        return toAjax(facDeviceBasicService.updateFacDeviceBasic(facDeviceBasic));
    }

    /**
     * 删除设备基础
     */
    @PreAuthorize("@ss.hasPermi('iot:basic:remove')")
    @Log(title = "设备基础", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(facDeviceBasicService.deleteFacDeviceBasicByIds(ids));
    }
    /**获取监测站点的设备集合-父级设备**/
    @GetMapping("/getDevicePList")
    public AjaxResult getDevicePList(FacDeviceBasic facDeviceBasic)
    {
        List<FacDeviceBasic> list = facDeviceBasicService.getDevicePList(facDeviceBasic);
        return AjaxResult.success(list);
    }
    /**根据设备ID获取子设备集合**/
    @GetMapping("/getChildDeviceById")
    public AjaxResult getChildDeviceById(FacDeviceBasic facDeviceBasic)
    {
        List<FacDeviceBasic> list = facDeviceBasicService.getChildDeviceById(facDeviceBasic);
        return AjaxResult.success(list);
    }


    /**
     * 设备上传图片
     */
    @PostMapping("/uploadImage/{deviceId}")
    public AjaxResult uploadFile(@PathVariable("deviceId")Long deviceId,
                                 List<MultipartFile> files) throws Exception {
        if(deviceId==null) {
            return AjaxResult.error("请选择设备进行上传!");
        }
        //查询设备是否存在
        FacDeviceBasic facDeviceBasic = facDeviceBasicService.selectFacDeviceBasicById(deviceId);
        if(facDeviceBasic==null){
            return AjaxResult.error("设备不存在!");
        }
        String bucket = deviceId.toString();
        List<FacDeviceFile> fileList = new ArrayList<>();
        try{
            for (MultipartFile file : files)
            {
                MinioFile upload = minioService.upload(bucket, file);
                if(upload==null){
                    continue;
                }
                FacDeviceFile facDeviceFile = new FacDeviceFile();
                facDeviceFile.setDeviceId(facDeviceBasic.getId());
                facDeviceFile.setFileName(upload.getFileName());
                facDeviceFile.setUrl(upload.getUrl());
                facDeviceFile.setObjectName(upload.getObjectName());
                facDeviceFile.setFileExt(upload.getFileExt());
                facDeviceFile.setFileSize(upload.getFileSize());
                facDeviceFile.setBucket(upload.getBucket());
                fileList.add(facDeviceFile);
                //保存
                facDeviceFileService.insertFacDeviceFile(facDeviceFile);
            }
        }catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(fileList);

    }


}
